<template>
	<view class="login-wechat">
		<view class="logo">
			<image class="avatar" src="/static/imgs/logo.png"></image>
			<text class="info">自助服务保</text>
		</view>
		<button class="btn" open-type="getPhoneNumber" @getphonenumber="getPhoneNumber">微信登录</button>
	</view>
</template>

<script>
	import {
		getOpenId,
		getMobile,
		wechatLogin
	} from '@/api/config'
	export default {
		data() {
			return {
				sessionKey: '',
				openid: '',
				encryptedData: '',
				iv: '',
			};
		},
		onLoad() {

		},
		methods: {
			// 获取手机号
			async getPhoneNumber(e) {
				this.$showLoading('登录中')
				this.encryptedData = e.detail.encryptedData
				this.iv = e.detail.iv
				const code = await this.getCode()
				const [idErr, idRes] = await getOpenId({
					code: code
				})
				if (idRes) {
					if (idRes.data.code != 200) {
						this.openid = idRes.data.data.openid
						this.sessionKey = idRes.data.data.session_key
						const [mobileErr, mobileRes] = await getMobile({
							sessionKey: this.sessionKey,
							iv: this.iv,
							encryptedData: this.encryptedData
						})
						if (mobileRes) {
							const [loginErr, loginRes] = await wechatLogin({
								phone: mobileRes.data.phoneNumber,
								openid: this.openid
							})
							uni.hideLoading()
							if (loginRes) {
								this.$storage.set('token', loginRes.data.token)
								this.$storage.set('userinfo', loginRes.data.data)
								uni.$emit('refresh')
								this.$open('/pages/maintenance/maintenance', 2)
							}
							if (loginErr) {
								this.$toast(loginErr.message)
							}
						}
						if (mobileErr) {
							uni.hideLoading()
							this.$toast(loginErr.message)
						}
					}
					if (idRes.data.code == 200) {
						uni.hideLoading()
						this.$storage.set('token', idRes.data.token)
						this.$storage.set('userinfo', idRes.data.data)
						uni.$emit('refresh')
						this.$open('/pages/maintenance/maintenance', 1)
					}
				}
				if (idErr) {
					uni.hideLoading()
					this.$toast(loginErr.message)
					return
				}
			},
			// 获取微信code
			async getCode() {
				const [providerErr, providerRes] = await uni.getProvider({
					service: 'oauth'
				})
				if (!~providerRes.provider.indexOf('weixin')) return
				const [err, res] = await uni.login({
					provider: 'weixin'
				})
				if (err) return
				return res.code
			},
		}
	}
</script>

<style lang="scss">
	@import '@/static/scss/config.scss';
	@import '@/static/scss/mixin.scss';

	page {
		@include square();
	}

	.login-wechat {
		@include square();

		@include flex-col(center) .logo {
			@include flex-col();

			.avatar {
				@include square(160rpx);
				margin-bottom: 30rpx;
			}

			@include font-set($font-c, $color-h, 500);
		}

		.btn {
			margin-top: 224rpx;
			@include box(690rpx, 100rpx, $bg-c);
			@include font-set($font-c, $color-b);
			@include flex-row();
		}
	}
</style>
